package main

import (
	"context"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"io/ioutil"
	"log"
	"os"
	authpb "serve/auth/api/gen/v1"
	"serve/auth/auth"
	"serve/auth/dao"
	"serve/auth/token"
	"serve/auth/wechat"
	"serve/settings"
	"serve/shared/server"
	"time"
)

func main() {
	err := settings.Init()
	if err != nil {
		log.Fatalf(" settings.Init() %v", err)
	}

	logger, err := server.NewZapLogger()
	if err != nil {
		log.Fatalf("cannot create logger err %v", err)
	}

	c := context.Background()            // 建立一个content
	MongoClient, err := mongo.Connect(c, // 创建mongo连接
		options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s:%d",
			viper.GetString("mongodb.user"),
			viper.GetString("mongodb.password"),
			viper.GetString("mongodb.host"),
			viper.GetInt("mongodb.port"),
		)))

	if err != nil {
		logger.Fatal("mongo.Connect err", zap.Error(err))
	}

	open, err := os.Open("./private.key")
	if err != err {
		logger.Fatal("os.Open(\"auth/private.key\")", zap.Error(err))
	}

	all, err := ioutil.ReadAll(open)
	if err != err {
		logger.Fatal("ioutil.ReadAll(open)", zap.Error(err))
	}
	pem, err := jwt.ParseRSAPrivateKeyFromPEM(all)
	if err != err {
		logger.Fatal(" jwt.ParseRSAPrivateKeyFromPEM(all)", zap.Error(err))
	}

	err = server.RunGRPCServer(&server.GrpcConfig{
		Name:              "auth",
		Addr:              viper.GetInt("auth.srv.port"),
		AuthPublicKeyFile: "",
		RegisterFunc: func(server *grpc.Server) {
			authpb.RegisterAuthServiceServer(server, &auth.Service{ //注册Auth服务
				Logger: logger, // 日志
				OpenIDResolver: &wechat.Service{ // 微信app OpenIDResolver  是一个接口， wechat.Service 是实现了这个接口的
					AppId:     viper.GetString("app.appid"),
					AppSecret: viper.GetString("app.app_secret"),
				},
				Mongo:       dao.NewMongo(MongoClient.Database(viper.GetString("mongodb.dbname"))), // Mongo连接
				TokenExpire: 2 * time.Hour,                                                         // token过期时间
				//TokenExpire:    10 * time.Second,                          // token过期时间
				TokenGenerator: token.NewJWTTokenGen("coolcar/auth", pem), // TokenGenerator 是一个接口 token.NewJWTTokenGen 是具体实现
			})
		},
		Logger: logger,
	})
	if err != nil {
		logger.Fatal("server.RunGRPCServer err", zap.Error(err))
	}
}
